//
//  PerfessionCertV2ViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/9.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "PerfessionCertV2ViewModel.h"

@interface PerfessionCertV2ViewModel()

@property (nonatomic, strong) ExpertDetailInfoData* detailInfoData;

@end

@implementation PerfessionCertV2ViewModel

#pragma mark - Ovrride
- (void)initialize
{
    [super initialize];
    
    @weakify(self)
    
    _isReload = NO;
    _isInPreview = NO;
    
    _waitDelIndexes = [NSMutableArray array];
    _personCertImages = [NSMutableArray array];
    _aboutCertImages = [NSMutableArray array];
    
    [[RACObserve(self, isInPreview) filter:^BOOL(id value) {
        
        BOOL result = [value boolValue];
        
        return result;
    }] subscribeNext:^(id x)
    {
        @strongify(self);
        
        self.waitDelIndexes = [NSMutableArray array];
    }];
    
    self.reloadCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        @weakify(self);
        return [[self _requestReloadSignal] doNext:^(id x)
                {
                    @strongify(self);
                    
                    [self _reload:x];
                }];
    }];
    
    self.addImgCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        EPUIImageData* epUIImageData = [EPUIImageData createWithImage:input imgData:nil];
        
        if (self.ctrlTag == 2000)
        {
            NSMutableArray* newUploadImgs = [NSMutableArray arrayWithArray:[self.personCertImages arrayByAddingObjectsFromArray:@[epUIImageData]]];
            self.personCertImages = newUploadImgs;
        }
        else if (self.ctrlTag == 2001)
        {
            NSMutableArray* newUploadImgs = [NSMutableArray arrayWithArray:[self.aboutCertImages arrayByAddingObjectsFromArray:@[epUIImageData]]];
            self.aboutCertImages = newUploadImgs;
        }
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    
    self.deleteImgCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        NSInteger delIndex = [input integerValue];
        
        EPUIImageData* delImgData = nil;
        
        if (self.ctrlTag == 2000)
        {
            delImgData = self.personCertImages[delIndex];
            
            [self.personCertImages removeObjectAtIndex:delIndex];
            self.personCertImages = [NSMutableArray arrayWithArray:self.personCertImages];
        }
        else if (self.ctrlTag == 2001)
        {
            delImgData = self.aboutCertImages[delIndex];
            
            [self.aboutCertImages removeObjectAtIndex:delIndex];
            self.aboutCertImages = [NSMutableArray arrayWithArray:self.aboutCertImages];
        }
        
        if (delImgData.imgData)
        {
            return [self requestDelImgSignal:delImgData.imgData];
        }
        else
        {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return nil;
            }];
        }
    }];
    
    self.deleteImgsCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        NSMutableArray* delImgs = [NSMutableArray array];
        
        if (self.ctrlTag == 2000)
        {
            for (NSNumber* delIndexNum in self.waitDelIndexes)
            {
                NSInteger delIndex = [delIndexNum integerValue];
                
                [delImgs addObject:self.personCertImages[delIndex]];
            }
            
            [self.personCertImages removeObjectsInArray:delImgs];
            NSMutableArray* newImgs = [NSMutableArray arrayWithArray:self.personCertImages];
            self.personCertImages = newImgs;
        }
        else if (self.ctrlTag == 2001)
        {
            for (NSNumber* delIndexNum in self.waitDelIndexes)
            {
                NSInteger delIndex = [delIndexNum integerValue];
                
                [delImgs addObject:self.aboutCertImages[delIndex]];
            }
            
            [self.aboutCertImages removeObjectsInArray:delImgs];
            NSMutableArray* newImgs = [NSMutableArray arrayWithArray:self.aboutCertImages];
            self.aboutCertImages = newImgs;
        }
        
        RACSignal* reqSignal = nil;
        
        for (NSInteger index=0; index<delImgs.count; index++)
        {
            EPUIImageData* uiimgData = delImgs[index];
            
            RACSignal* delImgSignal = [self requestDelImgSignal:uiimgData.imgData];
            
            if (reqSignal == nil)
            {
                reqSignal = delImgSignal;
            }
            else
            {
                reqSignal = [reqSignal then:^RACSignal *{
                    return delImgSignal;
                }];
            }
        }
        
        if (reqSignal)
            return reqSignal;
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    
    self.submitCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        @strongify(self);
        
        if (!self.strName || ![self.strName isNotBlank])
        {
            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请填写联系人"}]];
        }
        
        if (!self.strMobile || ![self.strMobile isNotBlank])
        {
            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请填写联系电话"}]];
        }
        
        if (self.personCertImages.count == 0)
        {
            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请上传个人身份证"}]];
        }
        
//        if (self.aboutCertImages.count == 0)
//        {
//            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请上传相关证书"}]];
//        }
        
        RACSignal* reqSignal = nil;
        
        for (NSInteger index=0; index<self.personCertImages.count; index++)
        {
            EPUIImageData* personCertImage = self.personCertImages[index];
            
            if (personCertImage.imgData!=nil)
            {
                continue;
            }
            
            RACSignal* uploadImgSignal = [[self requestUplaodImg:personCertImage.img type:@"1"] delay:1.0f];
            
            if (reqSignal == nil)
            {
                reqSignal = uploadImgSignal;
            }
            else
            {
                reqSignal = [reqSignal then:^RACSignal *{
                    return uploadImgSignal;
                }];
            }
        }
        
        for (NSInteger index=0; index<self.aboutCertImages.count; index++)
        {
            EPUIImageData* aboutCertImage = self.aboutCertImages[index];
            
            if (aboutCertImage.imgData!=nil)
            {
                continue;
            }
            
            RACSignal* uploadImgSignal = [[self requestUplaodImg:aboutCertImage.img type:@"2"] delay:1.0f];
            
            if (reqSignal == nil)
            {
                reqSignal = uploadImgSignal;
            }
            else
            {
                reqSignal = [reqSignal then:^RACSignal *{
                    return uploadImgSignal;
                }];
            }
        }
        
        if (reqSignal == nil)
        {
            return [self requestSubmitSignal];
        }
        
        @weakify(self);
        return [reqSignal then:^RACSignal *{
            @strongify(self);
            return [self requestSubmitSignal];
        }];
    }];
}

- (void)_reload:(ExpertDetailInfoData*)detailInfoData
{
    @weakify(self);
    
    self.detailInfoData = detailInfoData;
    
    self.strName = detailInfoData.expertInfo.contacts;
    self.strMobile = detailInfoData.expertInfo.mobile;
    self.strIntro = detailInfoData.expertInfo.summary;
    
    NSMutableArray* epimgDatas = [NSMutableArray arrayWithArray:detailInfoData.expertImage];
    
    NSMutableArray* keepPersonCertImgs = [NSMutableArray array];
    NSMutableArray* personCertEpImgDatas = [NSMutableArray array];
    
    NSMutableArray* keepAboutCertImgs = [NSMutableArray array];
    NSMutableArray* aboutCertEpImgDatas = [NSMutableArray array];
    
    for (NSInteger index=0; index<epimgDatas.count; index++)
    {
        EPImageData* curEPImgData = epimgDatas[index];
        NSInteger type = [curEPImgData.type integerValue];
        
        if (type == 1)
        {
            [personCertEpImgDatas addObject:curEPImgData];
        }
        else
        {
            [aboutCertEpImgDatas addObject:curEPImgData];
        }
    }
    
    [self _loadMoreImage:personCertEpImgDatas keepImgs:keepPersonCertImgs allFinish:^
     {
         @strongify(self);
         
         self.personCertImages = keepPersonCertImgs;
     }];
    
    [self _loadMoreImage:aboutCertEpImgDatas keepImgs:keepAboutCertImgs allFinish:^
     {
         @strongify(self);
         
         self.aboutCertImages = keepAboutCertImgs;
     }];
}

- (void)_loadMoreImage:(NSMutableArray*)imgDatas keepImgs:(NSMutableArray*)keepImgs allFinish:(VoidBlock)allFinish
{
    @weakify(self);
    
    if (imgDatas.count > 0)
    {
        EPImageData* imgData = imgDatas[0];
        
        [self _loadImage:imgData finish:^(UIImage* image)
         {
             @strongify(self);
             
             if (image)
             {
                 EPUIImageData* uiimageData = [EPUIImageData createWithImage:image imgData:imgData];
                 
                 [keepImgs addObject:uiimageData];
             }
             else
             {
                 NSLog(@"image为nil");
             }
             
             [imgDatas removeObjectAtIndex:0];
             
             [self _loadMoreImage:imgDatas keepImgs:keepImgs allFinish:allFinish];
         }];
    }
    else
    {
        allFinish();
    }
}

- (void)_loadImage:(EPImageData*)epImgData finish:(VoidBlock_id)finishBlock
{
    @weakify(self);
    
    UIImageView* imgview = [[UIImageView alloc] initWithFrame:(CGRect) {-10000, -10000, 100, 100}];
    [imgview yy_setImageWithURL:[NSURL URLWithString:epImgData.imageurl] placeholder:MHImageNamed(@"placeholderLogo") options:YYWebImageOptionIgnorePlaceHolder completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error)
     {
         @strongify(self);
         
         YYWebImageManager* manager = [YYWebImageManager sharedManager];
         NSString* key = [manager cacheKeyForURL:url];
         UIImage* curImg = [manager.cache getImageForKey:key];
         
         [imgview removeFromSuperview];
         
         finishBlock(curImg);
     }];
    [[UIViewController getCurrentVC].view addSubview:imgview];
}

- (RACSignal*)_requestReloadSignal
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    NSString* strUserID = um.userData.userID;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [[AFNetWorkUtils racPOSTWthURL:url_interface_expertInfo params:interface_param_expertInfo(strUserID)] subscribeNext:^(id x)
                 {
                     ExpertDetailInfoData* expertDetailInfoData = [ExpertDetailInfoData modelWithJSON:x];
                     
                     [subscriber sendNext:expertDetailInfoData];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"获取审核资料失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestUplaodImg:(UIImage*)image type:(NSString*)type
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    NSString* strUserID = um.userData.userID;
    NSString* reqType = type;
    
    CGSize uImgSize = image.size;
    UIImage* newUploadImg = [image hyb_clipToSize:(CGSize){100, 100*uImgSize.height/uImgSize.width} isEqualScale:YES];
    NSString* strImage = [UIImagePNGRepresentation(newUploadImg) base64EncodedStringWithOptions:0];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                NSLog(@"发起请求");
                
                [[AFNetWorkUtils racPOSTWthURL:url_interface_uploadexamineimage params:interface_param_uploadexamineimage(strUserID, strImage, reqType)] subscribeNext:^(id x)
                 {
                     NSLog(@"传输完毕");
                     [subscriber sendNext:[EPImageData modelWithJSON:x]];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSLog(@"传输完毕-错误");
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"上传图片失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestDelImgSignal:(EPImageData*)imageData
{
    @weakify(self);
    
    NSString* strImgID = imageData.imageID;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [[AFNetWorkUtils racPOSTWthURL:url_interface_deleteexamineimage params:interface_param_deleteexamineimage(strImgID)] subscribeNext:^(id x)
                 {
                     [subscriber sendNext:@YES];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"上传图片失败";
                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)requestSubmitSignal
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    NSString* strUserID = um.userData.userID;
    NSString* strExpertID = um.userDetailData.content.expertID;
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
    {
        @strongify(self);
        
        NSString* reqUrl = self.isReload ? url_interface_summaryedit : url_interface_submitexamine;
        NSDictionary* postData = self.isReload ? interface_param_summaryedit(strExpertID, self.strName, self.strMobile, self.strIntro, @"1") : interface_param_submitexamine(strUserID, self.strName, self.strMobile, self.strIntro);
        
        [[AFNetWorkUtils racPOSTWthURL:reqUrl params:postData] subscribeNext:^(id x)
         {
             [subscriber sendNext:x[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
         } error:^(NSError *error)
         {
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"提交专家审核失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

@end
